<template>
  <div class="app-container">
    <el-row class="search">
      <el-select v-model="query.t" style="margin-right: 8px; width: 120px" placeholder="日期类型">
        <el-option v-for="item in [
          { label: '出院日期', value: '出院日期' },
          { label: '入院日期', value: '入院日期' },
          { label: '在院', value: '在院' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-date-picker v-model="query.stime" style="width: 150px" type="date" placeholder="开始" value-format="yyyy-MM-dd">
      </el-date-picker>
      <span>-</span>
      <el-date-picker v-model="query.etime" style="width: 150px" type="date" value-format="yyyy-MM-dd" placeholder="结束">
      </el-date-picker>

      <el-select v-model="query.deptValue" style="margin-right: 8px; width: 120px" placeholder="科室">
        <el-option v-for="item in deptLs" :key="item.value" :label="item.text" :value="item.value"
          @click.native="科室change(item)">
        </el-option>
      </el-select>

      <el-select v-model="query.doctorValue" style="margin-right: 8px; width: 120px" placeholder="医生">
        <el-option v-for="item in doctors" :key="item.value" :label="item.text" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="query.st" style="margin-right: 8px; width: 120px" placeholder="状态">
        <el-option v-for="item in [
          { label: '状态', value: '' },
          { label: '已评估', value: '是否评估' },
          { label: '未入组', value: '未入组' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="query.warns" style="margin-right: 8px; width: 170px" placeholder="违规类别">
        <el-option v-for="item in 预警信息s" :key="item.id" :label="item.类别" :value="item.id">
        </el-option>
      </el-select>

      <el-select v-model="query.c" style="margin-right: 8px; width: 120px" placeholder="字段">
        <el-option v-for="item in [
          { label: '搜索字段', value: '' },
          { label: '病人姓名', value: '病人姓名' },
          { label: '住院号', value: '住院号' },
          { label: '病组编码', value: '病组编码' },
          { label: '病组名称', value: '病组名称' },
          { label: '诊断编码', value: '主要诊断编码' },
          { label: '诊断名称', value: '主要诊断名称' },
          { label: '手术编码', value: '主要手术编码' },
          { label: '手术名称', value: '主要手术名称' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-input v-model="query.s" prefix-icon="el-icon-search" style="width: 150px" placeholder="搜索关键字"
        @keyup.enter.native="search"></el-input>

      <el-button type="warning" @click="search" round>搜&nbsp;&nbsp;索</el-button>

      <el-dropdown @command="dropdownClick">
        <el-button type="danger">
          更多操作<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="onlymyself">仅看自己</el-dropdown-item>
          <el-dropdown-item command="showall">查看全部</el-dropdown-item>
          <el-dropdown-item command="evaluate">评价结果</el-dropdown-item>
          <!-- <el-dropdown-item command="designer">临床路径设计</el-dropdown-item> -->
          <el-dropdown-item command="refresh">刷新病人</el-dropdown-item>
          <!-- <el-dropdown-item command="useinfo">病人详情</el-dropdown-item> -->
          <!-- <el-dropdown-item command="export-form"
            >导出路径表单</el-dropdown-item
          > -->
          <!-- <el-dropdown-item>导入数据（暂不支持）</el-dropdown-item> -->
        </el-dropdown-menu>
      </el-dropdown>
    </el-row>
    <el-row>
      <el-table :data="patientLs" :header-cell-style="{ background: '#f2f2f2' }" border style="width: 100%"
        v-loading="isLoading" highlight-current-row @current-change="handleCurrentRowChange"
        @row-dblclick="handledbRow_Click" :cell-class-name="cellClassName" :height="height">
        <el-table-column type="index" width="50" fixed> </el-table-column>
        <el-table-column prop="fno" label="住院号" fixed width="100">
        </el-table-column>
        <el-table-column prop="patname" label="姓名" fixed> </el-table-column>

        <el-table-column prop="drgcode" label="病组编码" fixed>
          <template slot-scope="scope">
            <!-- <span
              style="color: #4682b4; font-weight: bold"
              v-if="scope.row.error"
              >{{ scope.row.error }}</span
            >
            <span v-else>{{ scope.row.drgcode }}</span> -->
            <span>{{ scope.row.drgcode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="drgname" show-overflow-tooltip label="病组名称" width="150" fixed>
        </el-table-column>
        <el-table-column label="状态" fixed>
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="(scope.row.路径ID || '') + '-' + (scope.row.路径名称 || '')
              " placement="right">
              <span style="font-weight: bold">{{
                scope.row.是否评估 ? "已评估" : ""
              }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="discode" label="诊断编码" fixed>
        </el-table-column>
        <el-table-column prop="disname" show-overflow-tooltip label="诊断名称" width="150">
        </el-table-column>
        <el-table-column prop="optcode" label="手术编码"> </el-table-column>
        <el-table-column prop="optname" label="手术名称" show-overflow-tooltip width="150">
        </el-table-column>
        <el-table-column prop="标杆来源" :formatter="标杆来源fmt" label="标杆来源" show-overflow-tooltip width="150">
        </el-table-column>
        <el-table-column label="总费用" width="120">
          <template slot-scope="scope">
            <el-tooltip v-if="!isEmpty(scope.row.标准总费用)" class="item" effect="dark"
              :content="fmt_content(scope.row.标准总费用)" placement="right">
              <span :style="{
                color:
                  scope.row.cost / scope.row.标准总费用 > 1.2
                    ? 'red'
                    : scope.row.cost / scope.row.标准总费用 < 0.8
                      ? 'blue'
                      : '',
              }">{{ scope.row.cost }}</span>
            </el-tooltip>
            <span :style="{
              color:
                scope.row.cost / scope.row.标准总费用 > 1.2
                  ? 'red'
                  : scope.row.cost / scope.row.标准总费用 < 0.8
                    ? 'blue'
                    : '',
            }" v-else>{{ scope.row.cost }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bed" label="床日">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准床日)" placement="right"
              v-if="!isEmpty(scope.row.标准床日)">
              <span>{{ scope.row.bed }}</span>
            </el-tooltip>

            <span v-else>{{ scope.row.bed }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rw" label="权重"> </el-table-column>
        <el-table-column prop="expended" label="药品费">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准药品费)" placement="right"
              v-if="!isEmpty(scope.row.标准药品费)">
              <span>{{ scope.row.expended }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.expended }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="surveyfee" label="检验费">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准检验费)" placement="right"
              v-if="!isEmpty(scope.row.标准检验费)">
              <span>{{ scope.row.surveyfee }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.surveyfee }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="examfee" label="检查费">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准检查费)" placement="right"
              v-if="scope.row.标准检查费">
              <span>{{ scope.row.examfee }}</span>
            </el-tooltip>

            <span v-else>{{ scope.row.examfee }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="治疗费" label="治疗费">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准治疗费)" placement="right"
              v-if="scope.row.标准治疗费">
              <span>{{ scope.row.治疗费 }}</span>
            </el-tooltip>

            <span v-else>{{ scope.row.治疗费 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="optfee" label="手术费">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准手术费)" placement="right"
              v-if="scope.row.标准手术费">
              <span>{{ scope.row.optfee }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.optfee }}</span>
          </template>
        </el-table-column>

        <el-table-column label="手术费占比">
          <template slot-scope="scope">
            <span>{{ ((scope.row.optfee || 0) / (scope.row.cost || 1) * 100).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="matfee" label="耗材费">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="fmt_content(scope.row.标准耗材费)" placement="right"
              v-if="scope.row.标准耗材费">
              <span>{{ scope.row.matfee }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.matfee }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="全自费" label="全自费"> </el-table-column>
        <el-table-column prop="科室" label="出院科室"> </el-table-column>
        <el-table-column prop="医生" label="医生"> </el-table-column>
        <el-table-column prop="itime" label="入院日期" width="120">
        </el-table-column>
        <el-table-column prop="otime" label="出院日期" width="120">
        </el-table-column>
        <el-table-column prop="rtime" label="刷新时间" width="150">
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.current"
          :page-sizes="[5, 10, 20, 50, 100, 200, 300, 400]" :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper" :total="query.total">
        </el-pagination>
      </div>
    </el-row>
  </div>
</template>

<script lang="ts">
import dayjs from "@/utils/dayjs.min.js";
import { Component, Vue } from "vue-property-decorator";
import {
  patientLs,
  sync,
  dept,
  doctor,
  formWord,
  checkWay,
  dept2doc,
  PreWarnMsg,
} from "@/api/patient";
import { Message, MessageBox, Row, Loading } from "element-ui";
import { RouteRecord, Route } from "vue-router";
import { getVersionName } from "@/utils/Utils";
import { UserModule } from "@/store/modules/user";
import axios from "axios";
import { setCookie, getCookie } from "@/utils/cookies";
import { userInfo } from "os";
@Component({
  name: "user",
})
export default class extends Vue {
  //搜索条件
  private showAllCookieKey = "showAllCookieKey";

  private height: number = 0;
  private autoHeight() {
    // 初始化的时候，设置高度
    this.setHeight();
    // 改变浏览器窗口大小的时候，设置高度
    window.addEventListener("resize", () => {
      this.setHeight();
    });
  }
  private setHeight() {
    this.$nextTick(() => {
      this.height = innerHeight - 200; // 这里的X就是顶部栏的高度
    });
  }
  private query = {
    stime: "" || this.$route.query.stime,
    etime: this.$route.query.etime || this.Format("yyyy-MM-dd", new Date()),
    s: this.$route.query.s || "",
    st: this.$route.query.st,
    page: 1,
    t: this.$route.query.t || (<any>window).MyConf["DataType"] || "在院",
    size: 10,
    total: 0,
    病组编码: this.$route.query.病组编码,
    路径名称: this.$route.query.路径名称,
    current: 1,
    deptValue: this.$route.query.deptValue || "",
    doctorValue:
      this.$route.query.doctorValue || getCookie(this.showAllCookieKey) || "",
    warns: "",
    c: this.$route.query.c || "",
  };

  private 标杆来源fmt(row: any) {
    let o: any = {
      1: "市级标杆",
      2: "本院标杆",
      3: "模板标杆",
    };

    return o[row.标杆来源];
  }
  private curUserName = UserModule.name;

  private isEmpty(val: any) {
    //var f = val == null;
    return !val;
  }

  private vn(code: string) {
    return getVersionName(code);
  }

  private fmt_content(val: any) {
    if (!val) return "";

    return val + "";
  }

  private fmt_扣减明细(row: any, col: any, val: any) {
    //console.log(row, val);
    if (val) {
      return val.split("|")[0];
    }
    return "";
  }

  private Format(fmt: string, date: Date) {
    //author: meizz
    var o: any = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }

    return fmt;
  }

  /**
 * //做超20%以上红色，不足80%蓝色，剩余的黑色
  private costChangeCss(val1: number, val2: number, val3: string) {
    if (val1 == 0) return "";

    let f = val1 / val2;
    if (val3 == "检查费" || val3 == "检验费") {
      return { costColorBlue: f < 0.8 };
    }
    return { costColorRed: f > 1.2 };
  }
 */
  private cellClassName(arg: any) {
    let row = arg.row;
    let col = arg.column;

    if (!col.label) return;

    let label = col.label;

    if (label.indexOf("费") < 0 && label !== "床日") return "";
    label = "标准" + label;

    // label=label.replace('费','费用')

    let fy = row[col.property];
    let fyStd = row[label];

    let r = (fy / fyStd) * 1.0;

    if (!fyStd) return "";

    // if (label.indexOf("检验") > -1 || label.indexOf("检验") > -1) {
    //   return r < 0.8 ? "fblue" : "";
    // }

    if (r < 0.8) {
      return "fblue";
    }
    // return r < 0.8 ? "fblue" : "";

    if (r > 1.2) return "fred";

    return "";
    // if (arg.row.是否评估) {
    //   return "ypg";
    // }
  }
  private currentRow: any;

  private async dropdownClick(command: string) {
    if (command == "onlymyself") {
      this.onlymyself(() => this.search());
      return;
    }

    if (command == "showall") {
      this.dept();
      this.query.doctorValue = "";
      setCookie(this.showAllCookieKey, this.query.doctorValue);
      this.search();
      return;
    }

    if (!this.currentRow) {
      this.$message.error("请选择要操作的行！（提示：单击数据行）");
      return;
    }

    // if (this.currentRow.bed > 60 || this.currentRow.bed < 2) {
    //   this.$message.error("当前床日大于60或小于2天,无法查看相关结果");
    //   return;
    // }
    let r = parseInt((Math.random() * 100).toString()).toString();

    if (command == "designer") {
      this.designer();
    }

    if (command == "useinfo") {
      this.$router.push({
        path: "/clinicalpathway/useinfo",
        query: { id: this.currentRow.id },
      });
    }
    if (command == "evaluate") {
      this.$router.push({
        path: "/clinicalpathway/evaluate2",
        query: {
          id: this.currentRow.id,
          r: r,
          patname: this.currentRow.patname,
        },
      });
    }
    if (command == "refresh") {
      const loading = this.$loading({
        text: `正在刷新【${this.currentRow.patname}】.....^_^`,
        lock: true,
        background: "rgba(255, 255, 255, 0.1)",
      });
      sync({ id: this.currentRow.id }).then((d: any) => {
        this.loadPatient();
        this.$message({
          type: "success",
          message: `【${this.currentRow.patname}】刷新成功!`,
        });
        loading.close();
      });
    }

    if (command == "export-form") {
      // formWord({id:this.currentRow.id}).then((rep:any)=>{
      //   console.log(rep)
      // })
      if (this.currentRow.drgcode) {
        let d: any = await checkWay({ id: this.currentRow.id });
        if (d.code == 0) {
          let pm = { id: this.currentRow.id, name: this.currentRow.patname };
          axios({
            method: "POST",
            baseURL: `${(<any>window).MyConf.APISERVICE}`,
            headers: { "X-Access-Token": UserModule.token },
            url: "/patient/form-word",
            params: pm,
            data: { id: this.currentRow.id },
            responseType: "blob", //返回是个文件
          }).then((response) => {
            // download(response, data); //then直接下载，方法在下边
            this.download(response, this.currentRow);
          });
        }
      } else {
        this.$message.warning("没有入组信息");
      }
    }
  }

  private download(res: any, data: any) {
    let blob = new Blob([res.data], { type: "application/vnd.ms-word" }); //type是文件类，详情可以参阅blob文件类型
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob);
    // 创建a标签，用于跳转至下载链接
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = blobURL;
    tempLink.setAttribute("download", `${data.fno}-${data.patname}.docx`);
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === "undefined") {
      tempLink.setAttribute("target", "_blank");
    }
    // 挂载a标签
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL);
  }
  private designer() {
    this.$router.push({
      path: "/clinicalpathway/designer",
      query: {
        id: this.currentRow.id,
      },
    });
  }
  //选中当前行
  private handleCurrentRowChange(val: any) {
    this.currentRow = val;
  }
  //行双击事件
  private handledbRow_Click() {
    this.dropdownClick("evaluate");
  }
  //每页改变事件
  private handleSizeChange(val: number) {
    this.query.size = val;
    this.query.page = 1;
    this.loadPatient();
  }
  //每页大小改变事件
  private handleCurrentChange(val: number) {
    this.query.page = val;
    this.loadPatient();
  }

  //查询
  private async search() {
    //console.log(arguments)
    this.query.page = 1;
    this.loadPatient();
  }
  private patientLs: any = [];

  private isLoading: boolean = true;
  //加载病人信息
  private async loadPatient() {
    this.isLoading = true;
    let q = JSON.parse(JSON.stringify(this.query));
    if (q.warns == "5") {
      q.warns = "5,6,7,8,9,10";
    }
    let patientData = await patientLs(q);
    this.patientLs = patientData.data.records;
    this.patientLs.forEach((it: any) => {
      if (it.itime) it.itime = it.itime.split(" ")[0];
      if (it.otime) it.otime = it.otime.split(" ")[0];
    });
    this.query.total = patientData.data.total;
    this.query.current = patientData.data.current;
    this.isLoading = false;
  }

  private r: number = 10;
  private async created() {
    await this.dept();

    // this.doctor();
    this.r = Math.random();
    let cDate = new Date();
    let m = cDate.getMonth() - ((<any>window).MyConf["TIMEINTERVAL"] || "1");
    cDate.setMonth(m);
    if (!this.query.stime) {
      this.query.stime = this.Format("yyyy-MM-dd", cDate);
      //this.query.stime = dayjs().subtract(3, "year").format("YYYY-MM-DD");
    }

    if (this.$route.query.page) {
      this.query.page = <any>this.$route.query.page;
    }
    if (this.$route.query.size) {
      this.query.size = <any>this.$route.query.size;
    }

    this.loadPatient();
    // this.onlymyself(() => {

    // });
    this.autoHeight();
    this.加载预警信息();
  }

  private 预警信息s: Array<any> = [];

  private async 加载预警信息() {
    const { data } = await PreWarnMsg({});
    this.预警信息s = [{ id: "", 类别: "所有" }, ...(data || [])];
  }

  private deptLs: Array<any> = [];

  private dept2docs: Array<any> = [];

  public async dept() {
    let curDate = new Date();
    let t = `${this.Format("yyyyMMddh", curDate)}${parseInt(
      curDate.getMinutes() / 5 + ""
    )}`;
    let d: any = await dept2doc({ t: t });

    d = d.data || [];
    let userdepts = await UserModule.GetUsername2depts();
    this.deptLs = [];
    //如果是医生，只查所属科室的
    if (userdepts.length > 0) {
      this.dept2docs = d.filter((it: any) => userdepts.filter((it2: any) => it2 == it.科室).length > 0);
      this.query.deptValue = userdepts[0]
    } else {
      this.dept2docs = d;
      this.deptLs.push({ text: "所有科室", value: "" })
    }
    let deptts = Array.from(new Set(this.dept2docs.map((it: any) => it.科室)));

    this.deptLs.push(...deptts.map((it: any) => ({ text: it, value: it })));
    this.医生列表("");
  }

  private 科室change(val: any) {
    this.医生列表(val.value);
  }

  private onlymyself(cb: Function) {
    this.doctors = [{ text: UserModule.name, value: UserModule.name }];

    this.deptLs = [
      { text: "所有科室", value: "" },
      ...this.dept2docs
        .filter((it: any) => it.医生 == UserModule.name)
        .map((it: any) => ({ label: it.科室, value: it.科室 })),
    ];

    setTimeout(() => {
      if (!this.query.doctorValue) {
        this.query.doctorValue = UserModule.name;
        setCookie(this.showAllCookieKey, this.query.doctorValue);
      }

      if (cb) cb();
    }, 100);
  }
  private 医生列表(d: string) {
    let ts = this.dept2docs;
    if (d) {
      ts = ts.filter((it: any) => it.科室 == d);
    }
    let docts = Array.from(new Set(ts.map((it: any) => it.医生)));
    this.doctors = [
      { text: "所有医生", value: "" },
      ...docts.map((it: any) => ({ text: it, value: it })),
    ];
  }

  private doctors: Array<any> = [];

  // public async doctor() {
  //   let curDate = new Date();
  //   let t = `${this.Format("yyyyMMddh", curDate)}${parseInt(
  //     curDate.getMinutes() / 5 + ""
  //   )}`;
  //   let d: any = await doctor({ t: t });
  //   d = d.data || [];
  //   this.doctors = [
  //     { text: "所有医生", value: "" },
  //     ...d.map((it: any) => ({ text: it, value: it })),
  //   ];
  // }
}
</script>

<style lang="scss">
.search {

  .el-input,
  .el-button {
    margin-left: 10px;
  }
}

.block {
  float: right;
  margin-top: 5px;
}

.ypg {
  color: blue !important;
}

// .el-table .cell {

//    white-space: nowrap;
// }
.fred {
  color: red;
}

.fblue {
  color: blue;
}

.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
